<script>
	import { ProgressStore } from './ProgressStore';

	// Guard code because thanks to `Astro.glob()`, this script will end up on
	// pages it is not intended to run on.
	if (
		window.location.pathname.endsWith('/tutorial/6-islands/3/') &&
		matchMedia('(prefers-reduced-motion: no-preference').matches
	) {
		// Dynamic import for code-splitting to avoid downloading unnecessarily.
		const { default: confetti } = await import('canvas-confetti');
		const fire = (particleRatio: number, opts: Parameters<typeof confetti>[0]) => {
			confetti({
				particleCount: Math.floor(200 * particleRatio),
				gravity: 2,
				...opts,
			});
		};
		const burst = () => {
			fire(0.25, { spread: 26, startVelocity: 55 });
			fire(0.2, { spread: 60 });
			fire(0.35, { spread: 100, decay: 0.91, scalar: 0.8 });
			fire(0.1, { spread: 120, startVelocity: 25, decay: 0.92, scalar: 1.2 });
			fire(0.1, { spread: 135, startVelocity: 45 });
		};

		let wasDone: boolean;
		ProgressStore.subscribePageDone(window.location.pathname, (done) => {
			if (done && wasDone === false) {
				burst();
				setTimeout(burst, 300);
			}
			wasDone = done;
		});
	}
</script>
